class UsersController < ApplicationController
  
  # User controller requires that account has been set and user is logged in
  before_filter :account_required, :login_required
  
  # Requires admin user for creating and destroying users
  before_filter :admin_required, :only => [:create, :destroy, :update]
  
  before_filter :find_user, :only => [:destroy, :edit, :update]
  
  # default page
  def index
    @users = User.find(:all, :conditions => ['company_id = ?', current_account.id])
  end
 
  # render new.rhtml
  def new
    @user = User.new
  end

  # Create user
  def create
    @user = User.new(params[:user])
    @user.company_id = current_account.id # User belongs to company
    @user.save
      if @user.errors.empty?
        flash[:notice] = "Thanks for signing up!"
        redirect_to users_path
      else
        flash.now[:error] = "There was an error saving user"
        render :action => 'new'
      end
  end
  
  # Show user
  def show
    @user = User.find_by_id(params[:id], :conditions => ['company_id = ?', current_account.id], 
    :include => :company)
    
    raise ActiveRecord::RecordNotFound, "Page not found" if @user.nil?
  end
  
  # Edit user
  def edit
  end
  
  # Update user
  def update
    if @user.update_attributes(params[:user])
      flash[:notice] = "Successfully updated profile"
      redirect_to user_path(@user, :subdomain => current_subdomain)
    else
      render :action => 'edit'
    end
  end
 
  
  # Destroys user and all data that belongs to it
  def destroy 
    if @user.destroy
      flash[:notice] = "Käyttäjä on poistettu"
      redirect_to users_path
    else
      flash.now[:error] = "Virhe poistettaessa käyttäjää"
      render :action => 'index'
    end
  end
  
  def access_denid
  end
  
  protected 
  
  def find_user
    @user = User.find_by_id(params[:id], :conditions => ['company_id = ?', current_account.id])
    raise ActiveRecord::RecordNotFound, "Page not found" if @user.nil?
  end
end
